<template>
  <div id="fileUpload">

      <a-upload
        name="avatar"
        :show-upload-list="false"
        :custom-request="handleUpload"
        :before-upload="beforeUpload"
      >
        <div v-if="user?.userAvatar">
        <a-space>
          <a-avatar :src="user?.userAvatar"
                    shape="square" :size="96" style="margin-left: 16px">
          </a-avatar>
        </a-space>
        </div>
        <div v-else>
          <a-avatar shape="square" :size="64">
            <template #icon><UserOutlined /></template>
          </a-avatar>
          <loading-outlined v-if="loading"></loading-outlined>
          <div class="ant-upload-text">上传头像</div>
        </div>
      </a-upload>
  </div>
</template>
<script lang="ts" setup>
import { ref } from 'vue';
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import type { UploadChangeParam, UploadProps } from 'ant-design-vue';
import { uploadPictureUsingPost } from '@/api/pictureController.ts'
import { testUploadFileUsingPost, uploadFileUsingPost } from '@/api/fileController.ts'

interface Props {
  user?: API.UserVO;
  biz?: string
}

const props = defineProps<Props>();

/**
 * 上传图片
 * @param file
 */
const handleUpload = async ({file}:any)=>{
  loading.value = true;
  try {
    const params = {};
    params.biz = props.biz;
    console.log("上传文件",params)
    const res =  await uploadFileUsingPost(params,{},file);
    if (res.data.code === 0 && res.data.data){
      message.success("图片上传成功");
    }else {
      message.error("图片上传失败" + res.data.message)
    }
  }catch (error){
    console.error("图片上传失败，"+error)
    message.error("图片上传失败" + error.message)
  }
  loading.value = false;
}

const loading = ref<boolean>(false);


/**
 * 上传前的校验
 * @param file
 */
const beforeUpload = (file: UploadProps['fileList'][number]) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('不支持上传该格式的图片，推荐 jpg 或 png!');
  }
  const isLt2M = file.size / 1024 / 1024 < 4;
  if (!isLt2M) {
    message.error('不能上传超过2MB的图片!');
  }
  return isJpgOrPng && isLt2M;
};
</script>
<style scoped>
#pictureUpload :deep(.ant-upload){
  width: 100% !important;
  height: 100% !important;
  min-height: 152px;
  min-width: 152px;
}

#pictureUpload img{
  max-width: 100%;
  max-height: 480px;
}

.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
